<?php
require 'Config.php';
class Mysql{
	private $link;
	private $sql;
	private $result;
	public function __construct(){
		$this->link = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_dbname);
		if(mysqli_connect_errno($this->link)){
			die('mysql链接错误：'.mysqli_error($this->link));
		}
		mysqli_query($this->link, 'SET NAMES '.DB_CHARSET);
	}

	public function insert($table, array $data){
		if(!is_array($data)) 
			throw new Exception("参数不正确，应该为数组", 1);
		
		$keys = array_keys($data);
		$fields = implode(',', $keys);//id,nickname,password
		$vals = array_values($data);
		$values = implode(',', $vals);

		$this->sql = "insert into `$table`($fields) VALUES($values)";
		return $this;
	}

	public function updata($table, array $data){
		//"update 表名 set 字段1=值1,字段2=值2 where 条件";
		$arr = array();

		foreach ($data as $key => $value) {
			$arr[] = "$key='$value'";
		}

		$this->sql = "update $table set ".implode(',', $arr);

		return $this;
	}

	public function delete($table){
		$this->sql = "delete from $table ";
		return $this;
	}

	public function select($table, $fields='*'){
		if(is_array($table)){
			$table = implode(',', $table);
		}

		$this->sql = "select $fields from $table ";

		return $this;
	}

	/**
	必须在select()或where()方法后调用
	*/
	public function orderBy(array $fields, $sort="DESC"){
		$this->sql .= " order by ".implode(',', $fields)." $sort ";
		return $this;
	}

	/**
	必须在select()、where()后调用
	*/
	public function limit($offset,$count){
		$this->sql .= " limit $offset, $count ";
		return $this;
	}

	/**
	必须在select()、update()、delete()方法后调用
	*/
	public function where($condition, $flag='and'){
		if(is_string($condition)){
			$this->sql .= " where $condition ";
		}
		else if(is_array($condition)){
			// 字段1=值1 and 字段2=值2
			$arr = array();

			foreach ($condition as $key => $value) {
				$arr[] = "$key='$value'";
			}

			$this->sql .= " where ".implode(" $flag ", $arr);
		}

		return $this;
	}

	/**
	必须在select()、update()、delete()、insert()
	或where()、limit()、orderBy()
	方法后调用
	*/
	public function query(){
		if(empty($this->sql)) return;

		if(!$this->link) $this->connect();

		$this->result = mysqli_query($this->link, $this->sql);
		$this->sql = null;

		return $this;
	}

	/**
	必须在query()方法后执行
	*/
	public function rows(){
		$arr = array();
		$str = "";
		if(!$this->result){
			return $arr;
		}
		if(!is_resource($this->result)){
			$str = $this->result;
			return $str;
		}
		while ($row = mysqli_fetch_assoc($this->result)) {
			array_push($arr, $row);
		}

		return $arr;
	}

	public function close(){
		if(is_object($this->link)){
			mysqli_close($this->link);			
			$this->link = null;
		}

		if($this->result){
			mysqli_free_result($this->result);
		}
	}

	public function __destruct(){
		$this->close();
	}
}
